package cn.ac.iie.di.ban.data.exchange.runner.slave.task.runTask;

import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.StatusEnum;
import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.task.order.TaskOrderRequest;
import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.task.order.TaskOrderResponse;
import cn.ac.iie.di.ban.data.exchange.runner.slave.task.checkTask.CheckSQLAndPermissionTask;
import cn.iie.jsqlparser.helper.JSQLParserHelper;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;

/**
 * Created by Black-Laptop on 12/9/2017.
 */
public class DownloadTask {

    private String errorMsg;
    private DownloadTaskThread downloadTaskThread;
    private JSQLParserHelper jsqlParserHelper;
//    private String resultPath;

    private String uniq_key;
    private String MMUrls;
    private String MMnameBase;
    private TaskOrderRequest taskOrderRequest;
    private String value;

    private String hdfsPath;


    private String ftpIp;
    private String ftpUser;
    private String ftpPassword;
    private int ftpPort;

    public DownloadTask(TaskOrderRequest taskOrderRequest, String MMUrls, String MMnameBase) throws Exception {
        this.MMUrls = MMUrls;
        this.MMnameBase = MMnameBase;

        this.taskOrderRequest = taskOrderRequest;
        this.uniq_key = taskOrderRequest.getUniq_key();
        this.errorMsg = "";

        this.value = getVaue();

        init(taskOrderRequest);
    }
//    public DownloadTask(TaskOrderRequest taskOrderRequest,String MMUrls,String MMnameBase,String ftpIp,int ftpPort,String ftpUser, String ftpPassword) throws Exception {
//        this.MMUrls = MMUrls;
//        this.MMnameBase = MMnameBase;
//        
//        this.taskOrderRequest = taskOrderRequest;
//        this.uniq_key = taskOrderRequest.getUniq_key();
//        this.errorMsg = "";
//        
//        this.value = getVaue();
//        
//        this.ftpIp = ftpIp;
//        this.ftpPort = ftpPort;
//        this.ftpUser = ftpUser;
//        this.ftpPassword = ftpPassword;
//        
//        init(taskOrderRequest);
//    }

    private String getVaue() throws Exception {
        JSQLParserHelper jsqlParserHelper = new JSQLParserHelper(taskOrderRequest.getSql());
        return jsqlParserHelper.getSQLWhereValues().get(0);
    }

    private void init(TaskOrderRequest taskOrderRequest) throws Exception {
        CheckSQLAndPermissionTask checkSQLAndPermissionTask = new CheckSQLAndPermissionTask(taskOrderRequest);
        TaskOrderResponse taskOrderResponse = checkSQLAndPermissionTask.checkSQLAndPermission(taskOrderRequest.getUniq_key());

        if (taskOrderResponse.getStatus() != StatusEnum.CHECK_SUCCESS) {
            throw new Exception("checkPermission error:" + taskOrderResponse.getDetail());
        }

        String sql = taskOrderResponse.getDetail();
        System.out.println("sql:" + sql);
        try {
            this.jsqlParserHelper = new JSQLParserHelper(sql);
        } catch (Exception e) {
            throw new Exception("sql error:" + sql);
        }
        setSql();
    }

    /**
     * 将channel.table转换成table
     *
     * @throws Exception
     */
    private void setSql() throws Exception {
        List<String> fromList = jsqlParserHelper.getSQLTables();
        List<String> fromListAfter = new ArrayList<String>();
        for (int i = 0; i < fromList.size(); i++) {
            String[] froms = fromList.get(i).split("\\.");
            fromListAfter.add(froms[froms.length - 1]);
        }
        jsqlParserHelper.setSQLTables(fromListAfter);
    }


    public TaskOrderResponse doDownloadTask() {
        TaskOrderResponse taskOrderResponse;
        Boolean downloadTaskRunSuccess = downloadTask();

        if (downloadTaskRunSuccess) {
            taskOrderResponse = setDoDownloadTaskSuccess();
        } else {
            taskOrderResponse = setDoDownloadTaskFail();
        }
        taskOrderResponse.setDetail("");

        return taskOrderResponse;
    }

    private TaskOrderResponse setDoDownloadTaskSuccess() {

        TaskOrderResponse taskOrderResponse = new TaskOrderResponse(uniq_key, StatusEnum.DOWNLOAD_TASK_SUCCESS, "");
        return taskOrderResponse;
    }

    private TaskOrderResponse setDoDownloadTaskFail() {

        TaskOrderResponse taskOrderResponse = new TaskOrderResponse(uniq_key, StatusEnum.DOWNLOAD_TASK_ERROR, errorMsg);
        return taskOrderResponse;
    }

    private Boolean downloadTask() {
        //一会看看
//        String sql = taskOrderRequest.getSql();        
        try {
//            this.jsqlParserHelper = new JSQLParserHelper(sql);
            downloadTaskThread = new DownloadTaskThread(taskOrderRequest, jsqlParserHelper, MMUrls, MMnameBase, value);

            downloadTaskThread.start();
        } catch (Exception e) {
            errorMsg = ExceptionUtils.getFullStackTrace(e);
            return false;
        }

        return true;
    }

    public Boolean getDownloadTaskThreadStatus() {
        return downloadTaskThread.isAlive();
    }

    public void stopDownloadTaskThread() {
        this.downloadTaskThread.stopThrad();
        while (true) {
            if (!downloadTaskThread.isAlive()) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
